import logging
import subprocess

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def get_temp():
    temp = float(subprocess.getoutput("vcgencmd measure_temp").split("=")[1].split("'")[0])
    return temp

def get_raspi4_power():
    """使用vcgencmd获取树莓派4的电压和频率信息"""
    try:
        # 获取核心电压
        volt = subprocess.check_output(['vcgencmd', 'measure_volts']).decode().strip()
        volt = float(volt.split('=')[1][:-1])
        
        # 获取CPU频率
        clock = subprocess.check_output(['vcgencmd', 'measure_clock', 'arm']).decode().strip()
        clock = int(clock.split('=')[1]) / 1e6  # 转换为MHz
        
        # 获取CPU温度
        temp = subprocess.check_output(['vcgencmd', 'measure_temp']).decode().strip()
        temp = float(temp.split('=')[1][:-2])
        
        return volt, clock, temp
    except Exception as e:
        print(f"Error getting power info: {e}")
        return 0, 0, 0

def estimate_power(volt, clock, temp):
    """树莓派4功耗估算公式"""
    # 基础功耗 (空闲时约1.5W)
    base_power = 1.5
    
    # 频率影响 (1.5GHz满载时约增加3W)
    freq_factor = min(clock / 1500, 1.0) * 3.0
    
    # 温度影响 (高温时功耗略增)
    temp_factor = max(0, (temp - 50) / 50) * 0.5
    
    estimated_power = base_power + freq_factor + temp_factor
    return estimated_power

